from rest_framework import serializers
from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
from django.contrib.auth.models import User


class SnippetSerializer(serializers.Serializer):
    id = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=True, max_length=100)
    code = serializers.CharField(style={'base_template': 'textarea.html'})
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES, default='friendly')

    def create(self, validated_data):
        """
        Create and return a new `Snippet` instance, given the validated data.
        """
        # 经过验证后的数据会存在 validated_data
        # 函数调用中，用** 表示传入一个dict, * 表示传入一个tuple
        return Snippet.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """
        Update and return an existing `Snippet` instance, given the validated data.
        """
        instance.title = validated_data.get('title', instance.title)
        instance.code = validated_data.get('code', instance.code)
        instance.linenos = validated_data.get('linenos', instance.linenos)
        instance.language = validated_data.get('language', instance.language)
        instance.style = validated_data.get('style', instance.style)
        instance.save()
        return instance



"""
    序列化 (Serialization)：将对象的状态信息转换为可以存储或传输的形式的过程。
    
    序列化过程
    from snippets.models import Snippet
    from snippets.serializers import SnippetSerializer
    from rest_framework.renderers import JSONRenderer
    from rest_framework.parsers import JSONParser

    1. 创建一个model实例,并保存
        snippet = Snippet(code='foo = "bar"\n')
        snippet.save()

    2. 序列化实例, 将模型实例转换为Python本地数据类型
        serializer = SnippetSerializer(snippet)
        serializer.data

    3. 继续序列化， 数据转化为json格式
        json = JSONRenderer().render(serializer.data)
        json


    反序列化

    1. parse a stream into Python native datatypes
        from django.utils.six import BytesIO
        stream = BytesIO(content)
        data = JSONParser().parse(stream)

    2. restore those native datatypes into a fully populated object instance.
        serializer = SnippetSerializer(data=data)
        serializer.is_valid()
        # True
        serializer.validated_data
        # OrderedDict([('title', ''), ('code', 'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])
        serializer.save()
        # <Snippet: Snippet object>

"""

#  使用modeliSerializer

class SnippetModelSerializer(serializers.ModelSerializer):
    """
    自动确定需要序列化的一系列属性
    默认实现了 create() 和 update() 方法
    """
    # 设置readonl 只读， 不修改，只返回值
    owner = serializers.ReadOnlyField(source='owner.username')
    class Meta:
        model = Snippet
        fields = ('id', 'title', 'code', 'linenos', 'language', 'style', 'owner')


class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ('id', 'username', 'snippets')
